package com.dabaozhan.modules.wx_app.facade.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import com.dabaozhan.common.utils.DateUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.util.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.dabaozhan.common.exception.RRException;
import com.dabaozhan.common.utils.ImageOperation;
import com.dabaozhan.common.utils.Utils;
import com.dabaozhan.modules.wx_app.base.PageResult;
import com.dabaozhan.modules.wx_app.dao.SiteOutRecordImgMapper;
import com.dabaozhan.modules.wx_app.entity.SaleFormEntity;
import com.dabaozhan.modules.wx_app.entity.SitOutRecourdQueryEntity;
import com.dabaozhan.modules.wx_app.entity.SiteOutBillQueryEntity;
import com.dabaozhan.modules.wx_app.entity.SiteOutRecordEntity;
import com.dabaozhan.modules.wx_app.entity.SiteOutRecordImgEntity;
import com.dabaozhan.modules.wx_app.enums.ResponseCodeEnum;
import com.dabaozhan.modules.wx_app.facade.SiteOutRecordFacade;
import com.dabaozhan.modules.wx_app.service.SaleFormService;
import com.dabaozhan.modules.wx_app.service.SiteOutRecordService;

@Service("siteOutRecordFacade")
public class SiteOutRecordFacadeImpl implements SiteOutRecordFacade{
	
	private static final Logger LOGGER = LoggerFactory.getLogger(SiteOutRecordFacade.class);
	
	@Autowired
	private SiteOutRecordService siteOutRecordService;

	@Autowired
	private SiteOutRecordImgMapper siteOutRecordImgMapper;
	
	@Autowired
	private SaleFormService saleFormService;
	
	//out arrive record
	private static final String ORDER_TAG="oar_";

	@Override
	public String addOutRecord(SiteOutRecordEntity entity,String pathUrl) {
		String orderSerial = ORDER_TAG+UUID.randomUUID().toString().replace("-","");
		//生成出库到厂流水号
		entity.setOrderSerial(orderSerial);
		//出库
		entity.setPlaceStatus(1);
		//未结算
		entity.setSettleStatus(1);
		String siteOutId = Utils.id().toString();
		entity.setId(siteOutId);
		int result = siteOutRecordService.addOutRecord(entity);
		if(result <=0){
			//未成功插入数据，抛出业务异常 在controller里面捕获
			throw new RRException(ResponseCodeEnum.ResponseCode_102.getCode(),ResponseCodeEnum.ResponseCode_102.getDescription());
		}
		
		List<String> picList = entity.getPictureList();
		//图片不为空  插入图片数据
		if(!CollectionUtils.isEmpty(picList)){
			for(int i=0;i<picList.size();i++){
				String picture = picList.get(i);
				if(i<=3 && !StringUtils.isEmpty(picture)){
					//获取文件目录图片 并保存到七牛
					String picUrl = "";
					try{
						picUrl = ImageOperation.encodeImage(picture.substring(picture.lastIndexOf("/") + 1), pathUrl);
					}catch(Exception e){
						LOGGER.error("上传并删除本地图片异常:",e);
					}
					if(StringUtils.isBlank(picUrl)){
						continue;
					}
					SiteOutRecordImgEntity imgEntity = new SiteOutRecordImgEntity();
					imgEntity.setId(Utils.id().toString());
					imgEntity.setSiteOutId(siteOutId);
					imgEntity.setPicUrl(picUrl);
					//1:出站 2:到厂
					imgEntity.setPicType(1);
					siteOutRecordImgMapper.addSiteOutRecordImg(imgEntity);
				}
			}
		}
		return orderSerial;
	}

	@Override
	public int updateArriveRecord(SiteOutRecordEntity entity) {
		if(StringUtils.isBlank(entity.getOrderSerial())){
			throw new RRException(ResponseCodeEnum.ResponseCode_101.getCode(),"orderSerial不能为空");
		}
		if(null == entity.getArriveGrossWeight()){
			throw new RRException(ResponseCodeEnum.ResponseCode_101.getCode(),"arriveGrossWeight不能为空");
		}
		if(null == entity.getArriveCargoWeight()){
			throw new RRException(ResponseCodeEnum.ResponseCode_101.getCode(),"arriveCargoWeight不能为空");
		}
		if(null == entity.getArriveTareWeight()){
			throw new RRException(ResponseCodeEnum.ResponseCode_101.getCode(),"arriveTareWeight不能为空");
		}
		if(null == entity.getArriveNetWeight()){
			throw new RRException(ResponseCodeEnum.ResponseCode_101.getCode(),"arriveNetWeight不能为空");
		}
		if(null == entity.getArriveOffOther()){
			throw new RRException(ResponseCodeEnum.ResponseCode_101.getCode(),"arriveOffOther不能为空");
		}
		if(null == entity.getArriveOffWater()){
			throw new RRException(ResponseCodeEnum.ResponseCode_101.getCode(),"arriveOffWater不能为空");
		}
		if(null == entity.getArrivePrice()){
			throw new RRException(ResponseCodeEnum.ResponseCode_101.getCode(),"arrivePrice不能为空");
		}
		if(null == entity.getArriveMoney()){
			throw new RRException(ResponseCodeEnum.ResponseCode_101.getCode(),"arriveMoney不能为空");
		}
		if(null == entity.getArrivePacketNumber()){
			throw new RRException(ResponseCodeEnum.ResponseCode_101.getCode(),"arrivePacketNumber不能为空");
		}
		if(null == entity.getSettleStatus()){
			throw new RRException(ResponseCodeEnum.ResponseCode_101.getCode(),"settleStatus不能为空");
		}
		
		int result = siteOutRecordService.updateArriveRecord(entity);
		if(result <=0){
			throw new RRException(ResponseCodeEnum.ResponseCode_107.getCode(),ResponseCodeEnum.ResponseCode_107.getDescription());
		}
		SiteOutRecordEntity recordInfo = siteOutRecordService.getRecordByOrderSerial(entity.getOrderSerial());
		if(null != recordInfo){
			//到厂数据录入销货报表
			SaleFormEntity saleFormEntity = new SaleFormEntity();
			//单价
			saleFormEntity.setArrivePrice(recordInfo.getArrivePrice());
			//品类id
			saleFormEntity.setCategoryId(recordInfo.getCategoryId());
			//品类父id
			saleFormEntity.setParentId(recordInfo.getParentId());
			//厂名
			saleFormEntity.setName(recordInfo.getDestination());
			//总重量
			saleFormEntity.setTotalWeight(recordInfo.getArriveNetWeight());
			//总价
			saleFormEntity.setTotalPrice(recordInfo.getArriveMoney());
			//打包站id
			saleFormEntity.setUserId(recordInfo.getUserId());
			//添加到厂记录
			saleFormService.saveSaleForm(saleFormEntity);
		}
		return result;
	}

	@Override
	public PageResult<List<SiteOutRecordEntity>> getBalanceBill(SiteOutBillQueryEntity entity) {
		//时间区间 1:全部 2:近7天 3:近1个月 4:近3个月 5:3个月前
		int tomeSection = entity.getTimeSection();
		Date beginDate = DateUtils.getBeginDate(tomeSection);
		Date endDate = DateUtils.getEndDate(tomeSection);
		long totalCount = siteOutRecordService.getBalanceBillCountForPage(entity.getUserId(), entity.getSettleStatus(), beginDate, endDate);
		if(totalCount <=0){
			throw new RRException(ResponseCodeEnum.ResponseCode_400.getCode(),ResponseCodeEnum.ResponseCode_400.getDescription());
		}
		//查询开始区间
		int beginIndex = (entity.getPage()-1)*entity.getSize();
		//查询结束区间
		int endIndex = entity.getPage()*entity.getSize();
		List<SiteOutRecordEntity> list = siteOutRecordService.getBalanceBill(entity.getUserId(), entity.getSettleStatus(), beginDate, endDate,beginIndex,endIndex);
		if(CollectionUtils.isEmpty(list)){
			throw new RRException(ResponseCodeEnum.ResponseCode_400.getCode(),ResponseCodeEnum.ResponseCode_400.getDescription());
		}
		PageResult<List<SiteOutRecordEntity>> pageResult = new PageResult<List<SiteOutRecordEntity>>();
		pageResult.setTotal(totalCount);
		pageResult.setListData(list);
		return pageResult;
	}

	@Override
	public PageResult<List<SiteOutRecordEntity>> getOutRecord(SitOutRecourdQueryEntity entity) {
		Integer placeStatus = null;
		//出库未到厂数据
		if(entity.getDataType() == 2){
			placeStatus = 1;
		}
		long totalCount = siteOutRecordService.getOutRecordCountForPage(entity.getUserId(), placeStatus);
		if(totalCount <=0){
			throw new RRException(ResponseCodeEnum.ResponseCode_400.getCode(),ResponseCodeEnum.ResponseCode_400.getDescription());
		}
		//查询开始区间
		int beginIndex = (entity.getPage()-1)*entity.getSize();
		//查询结束区间
		int endIndex = entity.getPage()*entity.getSize();
		List<SiteOutRecordEntity> list = siteOutRecordService.getOutRecord(entity.getUserId(),placeStatus,beginIndex,endIndex);
		if(CollectionUtils.isEmpty(list)){
			throw new RRException(ResponseCodeEnum.ResponseCode_400.getCode(),ResponseCodeEnum.ResponseCode_400.getDescription());
		}
		for(SiteOutRecordEntity outRecord:list){
			List<String> pictureList = new ArrayList<String>();
			List<SiteOutRecordImgEntity> imgList = siteOutRecordImgMapper.getSiteOutImgEntity(outRecord.getId());
			if(!CollectionUtils.isEmpty(imgList)){
				for(SiteOutRecordImgEntity imgEntity:imgList){
					pictureList.add(imgEntity.getPicUrl());
				}
			}
			outRecord.setPictureList(pictureList);
		}
		PageResult<List<SiteOutRecordEntity>> pageResult = new PageResult<List<SiteOutRecordEntity>>();
		pageResult.setTotal(totalCount);
		pageResult.setListData(list);
		return pageResult;
	}

	@Override
	public int updateSettleStatus(SiteOutRecordEntity entity) {
		int result = siteOutRecordService.updateSettleStatus(entity);
		if(result <=0){
			throw new RRException(ResponseCodeEnum.ResponseCode_107.getCode(),ResponseCodeEnum.ResponseCode_107.getDescription());
		}
		return result;
	}


}
